#include "userrepository.h"
#include "jsonconfigwriter.h"

#include <QVariantMap>

UserRepository::UserRepository(const QString &uiPath)
    : m_uiPath(uiPath)
{

     setUiPath(uiPath);     
}

void UserRepository::setUiPath(const QString &uiPath)
{
    m_uiPath = uiPath;
    if (m_jsonconfigwriter) {
            delete m_jsonconfigwriter;
    }
    m_jsonconfigwriter = new JsonConfigWriter(nullptr, m_uiPath);
}

QStringList UserRepository::loadUsers() const
{
    QVariantMap Ui_JsonRoot;
    QVariantMap UserMap = m_jsonconfigwriter->Read_Ui_UserMap(Ui_JsonRoot);
    UserMap = Ui_JsonRoot["users"].toMap();
    return UserMap.value("users").toStringList();
}

void UserRepository::addUser(const QString &username, const QStringList &hiddenCtrls)
{

    // 写入用户专属 UI 配置
    if (!m_uiPath.isEmpty()) {
        m_jsonconfigwriter->Write_To_Ui_Json(username, hiddenCtrls);
    }

    // 更新全局 users.json
    QVariantMap User_JsonRoot;
    QVariantMap UserMap = m_jsonconfigwriter->Read_Ui_UserMap(User_JsonRoot);
    QStringList users = UserMap["users"].toStringList();
    if (!users.contains(username))
        users << username;
    User_JsonRoot["users"] = users;
    m_jsonconfigwriter->saveMapToJson(m_jsonconfigwriter->makeUsersPath(),User_JsonRoot);
}

void UserRepository::deleteUser(const QString &username)
{
    // 删除 UI 专属配置
    if (m_jsonconfigwriter &&!m_uiPath.isEmpty()) {
        m_jsonconfigwriter->remove_User_From_Ui_Json(username);
    }
}
